// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import {TimePicker , Form,Radio, Tooltip, Button,Popconfirm, Modal, Row, Col, Input, Select, Cascader, Icon, Checkbox, Tabs, DatePicker, message } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './otherConfigAddStyle.less'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import moment from 'moment';

const FormItem = Form.Item
const { RangePicker } = DatePicker
const InputGroup = Input.Group;
const { Option } = Select;


/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const otherConfigAddView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue ,validateFieldsAndScroll} = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let { areaList,products,query, actionType, btnLoading } = modelObj
  if(query.areaId){
    form.resetFields()
  }
  const formItemLayoutPro = {
    labelCol: { span: 6 },
    wrapperCol: { span: 8 },
  };
  const formItemLayoutPro1 = {
    labelCol: { span: 12 },
    wrapperCol: { span: 12 },
  };

  // 自定义双选下拉
class PriceInput extends React.Component {
  handleNumberChange = e => {
    const number = parseInt(e.target.value || 0, 10);
    if (isNaN(number)) {
      return;
    }
    this.triggerChange({ number });
    query.ztBbbhq = number
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {query}
    })
  };

  handleCurrencyChange = currency => {
    this.triggerChange({ currency });
    query.ztBbbhqUnit = currency
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {query}
    })
  };

  triggerChange = changedValue => {
    const { onChange, value } = this.props;
    if (onChange) {
      onChange({
        ...value,
        ...changedValue,
      });
    }
  };

  render() {
    const { size, value } = this.props;
    return (
      <span>
        <Input
          type="text"
          size={size}
          value={value.number}
          onChange={this.handleNumberChange}
          style={{ width: '65%', marginRight: '3%' }}
        />
        <Select
          value={value.currency}
          size={size}
          style={{ width: '32%' }}
          onChange={this.handleCurrencyChange}
        >
          <Option value="1">天</Option>
          <Option value="2">小时</Option>
        </Select>
      </span>
    );
  }
}


  function goback(){
    hashHistory.push({
      pathname: '/home/expandManage/configurationCenter',
      query: {tabsType:"1"}
    });
  }
  
  function timeChange (value, name) {
    let obj = {[name]: value}
    query = Object.assign(query, obj)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {query}
    })
  }
  //输入框改变时
  function inputChange(e, name) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: e,
        }
      }
    })
  }
  //区域改变时
  function inputAreaChange(value, name) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: value,
        }
      }
    })
    filterProjectList(value)
  }
  // 添加保护期校验
  function checkPrice(rule, value, callback){
    if (value.number > 0) {
      return callback();
    }
    callback('请输入保护期');
  }
  
  //过滤项目数据
  function filterProjectList(areaId){
    let list = []
    for(var item of areaList){
      if(item.value == areaId){
        list = item.children
      }
    }
    if(list.length){
      products =  list.map((item,index)=>{
        return {
          label: item.buname,
          value: item.buguid,
        }
      })
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {products}
    })
  }

  function checkboxChange (checkedValues, name) {
    let obj = {[name]: checkedValues}
    query = Object.assign(query, obj)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {query}
    })
  }
  function radioChange(checkedValues, name){
    // if(checkedValues == '0'){
    //   query.pmStartTime = ''
    //   query.pmEndTime = ''
    //   query.pmBeePay = ''
    // }
    let obj = {[name]: checkedValues}
    query = Object.assign(query, obj)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {query}
    })
  }
  function submit(){
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/submit`,
          payload: {},
          callback:()=>{
            hashHistory.push({
              pathname: '/home/expandManage/configurationCenter',
              query: {tabsType:"1",areaId:query.areaId,projectId:query.projectId}
            })
          }
        })
      }
    })
  }

  return (
    <div className='public_listMain'>
      <div className={"functionButton"}>
        <Popconfirm placement="top" title={"是否确认关闭，确认后关闭页面，不保存数据。"} onConfirm={() => goback()} okText="确定" cancelText="取消">
          <Button>返回</Button>
        </Popconfirm>
        <Button type='primary' onClick={e => submit()} loading={btnLoading}>提交</Button>
      </div>

      <CollapsiblePanels title="参数配置详情" hideUpDownBtn={true} >
    
        <Row>
          <Col span={16}>
            <FormItem label='区域'  {...formItemLayoutPro}>
              {getFieldDecorator('areaId', {
                rules: [{
                  required: true, whitespace: true, message: '请选择区域'
                }],
                initialValue: query.areaId
              })(
                <Select placeholder='请选择区域' onChange={(e) => { inputAreaChange(e, 'areaId') }}>
                  {/* <Select.Option value="A7319161253">重庆区域</Select.Option>
                   */}
                   {areaList.map((item)=>{
                      return <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
                    })}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={16}>
            <FormItem label='项目'  {...formItemLayoutPro}>
              {getFieldDecorator('projectId', {
                rules: [{
                  required: true, whitespace: true, message: '请选择项目'
                }],
                initialValue: query.projectId
              })(
                <Select  placeholder='请选择项目' onChange={(e) => { inputChange(e, 'projectId') }}>
                    {products.map((item)=>{
                        return <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
                      })}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={16}>
            <FormItem label='渠道经理查看客户全号'  {...formItemLayoutPro}>
              {getFieldDecorator('phoneAuthority', {
                rules: [{
                  required: false, whitespace: true, message: '请选择'
                }],
                initialValue: query.phoneAuthority
              })(
                <Radio.Group name="phoneAuthority" onChange={(e) => { checkboxChange(e.target.value, 'phoneAuthority') }}>
                    <Radio value='1'>允许</Radio>
                    <Radio value='0'>不允许</Radio>
                </Radio.Group>
              )}
            </FormItem>
            <Tooltip
                  title={'允许：经理查看其他人客户电话号码为全号显示；不允许：经理查看他人客户仅显示前三后四电话号码'}
              >
                <Icon style={{color:'#0877fd',fontSize:'18px',position: 'absolute',left: '41%',top: '15px',zIndex: 999}} type="question-circle" />
            </Tooltip>
          </Col>
        </Row>
        <Row>
          <Col span={16}>
            <FormItem label='是否允许指定置业顾问'  {...formItemLayoutPro}>
              {getFieldDecorator('isAllowsSpecify', {
                rules: [{
                  required: false, whitespace: true, message: '请选择'
                }],
                initialValue: query.isAllowsSpecify
              })(
                <Radio.Group name="isAllowsSpecify" onChange={(e) => { checkboxChange(e.target.value, 'isAllowsSpecify') }}>
                    <Radio value='1'>允许</Radio>
                    <Radio value='0'>不允许</Radio>
                </Radio.Group>
              )}
            </FormItem>
            <Tooltip
                  title={'允许：在智行销APP报备客户时，能选择置业顾问；不允许：在智行销APP报备客户时，不能选择置业顾问'}
              >
                <Icon style={{color:'#0877fd',fontSize:'18px',position: 'absolute',left: '41%',top: '15px',zIndex: 999}} type="question-circle" />
            </Tooltip>
          </Col>
        </Row>
        <Row>
          <Col span={16}>
            <FormItem label='是否允许报备业主（其他项目）'  {...formItemLayoutPro}>
              {getFieldDecorator('ifAllowCrossProject', {
                rules: [{
                  required: false, whitespace: true, message: '请选择'
                }],
                initialValue: query.ifAllowCrossProject
              })(
                <Radio.Group name="ifAllowCrossProject" onChange={(e) => { checkboxChange(e.target.value, 'ifAllowCrossProject') }}>
                    <Radio value='1'>允许</Radio>
                    <Radio value='0'>不允许</Radio>
                </Radio.Group>
              )}
            </FormItem>
            <Tooltip
                  title={'允许：该项目可以报备美的置业业主；不允许：该项目不可报备美的置业业主'}
              >
                <Icon style={{color:'#0877fd',fontSize:'18px',position: 'absolute',left: '41%',top: '15px',zIndex: 999}} type="question-circle" />
            </Tooltip>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='报备到访最短有效时间'  {...formItemLayoutPro1}>
              {getFieldDecorator('callbackShortTime', {
                rules: [{
                  required: false, whitespace: true, message: '请选择'
                }],
                initialValue: query.callbackShortTime
              })(
                <Input 
                  onChange={(e) => { inputChange(e.target.value, 'callbackShortTime') }}
                />
              )}
            </FormItem>
          </Col>
          <Col span={2}>
            <span style={{margin:'0 10px'}}>小时</span>  
              <Tooltip
                    title={'作为扫码判客的提示，必须在报备时间+到访最短有效时间后且在合同有效期内，到访才有效，支持小数点后2位数'}
                >
                  <Icon style={{color:'#0877fd',fontSize:'18px',marginTop:'10px'}} type="question-circle" />
              </Tooltip>
          </Col>
          {query.callbackShortTime &&
            <Col span={2}> 
              <div style={{color:'#0877fd',marginTop:'10px'}}>等于{query.callbackShortTime*60}分钟</div>
            </Col>
          }
          
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='报备到访最长有效时间'  {...formItemLayoutPro1}>
              {getFieldDecorator('callbackLongTime', {
                rules: [{
                  required: false, whitespace: true, message: '请选择'
                }],
                initialValue: query.callbackLongTime
              })(
                <Input 
                  onChange={(e) => { inputChange(e.target.value, 'callbackLongTime') }}
                />
              )}
            </FormItem>
          </Col>
          <Col span={2}>
            <span style={{margin:'0 10px'}}>小时</span>  
              <Tooltip
                    title={'客户必须在报备时间+到访最长有效时间内到访才有效，逾期未到访需重新报备客户'}
                >
                  <Icon style={{color:'#0877fd',fontSize:'18px',marginTop:'10px'}} type="question-circle" />
              </Tooltip>
          </Col>
          {query.callbackLongTime &&
            <Col span={2}> 
              <div style={{color:'#0877fd',marginTop:'10px'}}>等于{query.callbackLongTime*60}分钟</div>
            </Col>
          }
        </Row>
        <Row>
          <Col span={16}>
            <FormItem label='考勤规则'  {...formItemLayoutPro}>
              {getFieldDecorator('type', {
                rules: [{
                  required: false, whitespace: true, message: '请选择'
                }],
                initialValue: query.type
              })(
                <Radio.Group name="type" onChange={(e) => { radioChange(e.target.value, 'type') }}>
                    <Radio value='0'>一天一班</Radio>
                    <Radio value='1'>一天两班</Radio>
                </Radio.Group>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col style={{textAlign: 'right',lineHeight: '42px'}}  span={2}>白班</Col>
          <Col span={6}>
            <FormItem label='上班时间'  {...formItemLayoutPro}>
              {getFieldDecorator('amStartTime', {
                initialValue: query.amStartTime
              })(
                // <TimePicker  format={"HH:mm"} onChange={(e) => { timeChange(e._i, 'amStartTime') }}/>
                <Input type="time" onChange={(e) => { inputChange(e.target.value, 'amStartTime') }}/>
              )}
            </FormItem>
          </Col>
          <Col span={6}>
            <FormItem label='下班时间'  {...formItemLayoutPro}>
              {getFieldDecorator('amEndTime', {
                initialValue: query.amEndTime
              })(
                // <TimePicker  format={"HH:mm"} onChange={(e) =>{ timeChange(e._i, 'amEndTime') }}/>
                <Input type="time" onChange={(e) => { inputChange(e.target.value, 'amEndTime') }}/>
              )}
            </FormItem>
          </Col>
          <Col span={10}>
            <FormItem label='小蜜蜂费用'  {...formItemLayoutPro}>
              {getFieldDecorator('amBeePay', {
                rules: [{
                  required: false, whitespace: true, message: '请选择'
                }],
                initialValue: query.amBeePay
              })(
                <Input  addonAfter="元/人天"  onChange={(e) => { inputChange(e.target.value, 'amBeePay') }}/>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row style={{display: query.type=='1'?'block':'none'}}>
          <Col style={{textAlign: 'right',lineHeight: '42px'}} span={2}>晚班</Col>
          <Col span={6}>
            <FormItem label='上班时间'  {...formItemLayoutPro}>
              {getFieldDecorator('pmStartTime', {
                initialValue: query.pmStartTime
              })(
                // <TimePicker  format={"HH:mm"} onChange={(e) => { timeChange(e._i, 'pmStartTime') }}/>
                <Input type="time" onChange={(e) => { inputChange(e.target.value, 'pmStartTime') }}/>
              )}
            </FormItem>
          </Col>
          <Col span={6}>
            <FormItem label='下班时间'  {...formItemLayoutPro}>
              {getFieldDecorator('pmEndTime', {
                initialValue: query.pmEndTime
              })(
                // <TimePicker  format={"HH:mm"} onChange={(e) => { timeChange(e._i, 'pmEndTime') }}/>
                <Input  type="time" onChange={(e) => { inputChange(e.target.value, 'pmEndTime') }}/>
              )}
            </FormItem>
          </Col>
          <Col span={10}>
            <FormItem label='小蜜蜂费用'  {...formItemLayoutPro}>
              {getFieldDecorator('pmBeePay', {
                rules: [{
                  required: false, whitespace: true, message: '请选择'
                }],
                initialValue: query.pmBeePay
              })(
                <Input addonAfter="元/人天" onChange={(e) => { inputChange(e.target.value, 'pmBeePay') }}/>
              )}
            </FormItem>
          </Col>
        </Row>
      </CollapsiblePanels>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(otherConfigAddView))